﻿using _2008A.PH5._0221_0317.FuXi.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace _2008A.PH5._0221_0317.FuXi.API.Controllers
{
    [Route("car")]
    [ApiController]
    public class ShoppingCarController : ControllerBase
    {

        /*
         * 购物车用Redis实现
         * 1、连接Redis服务器
         *      1）先安装CsRedisCore
         *      2）new 一个 CsRedisClient对象
         * 2、用刚才new的对象，实现CRUD
         * **/
        //IConfiguration _configuration;
        CSRedis.CSRedisClient _client;
        NLog.Logger _log;

        ILogService _logService;
        IProductService _productService;
        public ShoppingCarController(ILogService logService, IProductService productService)
        {
            //_configuration = configuration;
            //new CSRedis.CSRedisClient($"{  configuration.GetSection("RedisConfig:Host").Value}:{  configuration.GetSection("RedisConfig:Port").Value}");
            _client = new CSRedis.CSRedisClient("127.0.0.1:6379");

            _log = NLog.LogManager.GetCurrentClassLogger();
            _logService = logService;
            _productService = productService;   
        }

        /// <summary>
        /// 添加购物车
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Insert(ShoppingCarDto dto)
        {
            #region //判断库存
            //得先拿到库存数量
            var model = _productService.Query().Where(x => dto.ProductId.Equals(x.Id.ToString())).FirstOrDefault();
            if(dto.ProductNumber > model.Stock)
            {
                return BadRequest(new { code = 200, message = "库存不足", statue = false });
            }
            #endregion



            string key = dto.MemberId;

            //因为购物车中，会存放很多品种的商品，所以redis应该放什么数据结构 --- List

            //放进去之前，需要看看redis里有没有这个用户的数据，所以需要先拿出来
            var data = _client.Get<List<ShoppingCarDto>>(key);

            if (data == null)
            {
                List<ShoppingCarDto> list = new();
                list.Add(dto);
                _client.Set(key, list);
            }
            else
            {
                //如果原来存在商品数据，那么要去看看，有没有和要添加的这个商品一样的，如果有一样的，则数量累加
                var m = data.Where(x => dto.ProductId.Equals(x.ProductId)).FirstOrDefault();
                if (m != null)
                {
                    m.ProductNumber += dto.ProductNumber;
                    if(m.ProductNumber > model.Stock)
                    {
                        return BadRequest(new { code = 200, message = "库存不足", statue = false });
                    }
                }
                else
                {
                    data.Add(dto);
                }
                _client.Set(key, data);
            }
            return Ok(new { code = 200, message = "success" });
        }


        [HttpDelete]
        public IActionResult Delete(List<ShoppingCarDto> dtos)
        {
            string key = dtos[0].MemberId;
            //要删除数据，是从redis里面删除，所以要先把数据从redis中拿出来
            var data = _client.Get<List<ShoppingCarDto>>(key);

            dtos.ForEach(x =>
            {
                var m = data.Where(p => p.ProductId == x.ProductId).FirstOrDefault();
                if(m !=null)
                {
                    //删除的时候写入日志
                    _log.Info(m); 
                    //删除的时候，写入数据库
                    _logService.Insert(new Domain.LogEntity { Content = Newtonsoft.Json.JsonConvert.SerializeObject(m) });

                    data.Remove(m);
                }
            });
            _client.Set(key, data);
            return Ok(new { code = 200, message = "success" });
        }


        [HttpPut]
        public IActionResult Update(ShoppingCarDto dto)
        {

            #region //判断库存
            //得先拿到库存数量
            var model = _productService.Query().Where(x => dto.ProductId.Equals(x.Id.ToString())).FirstOrDefault();
            if (dto.ProductNumber > model.Stock)
            {
                return BadRequest(new { code = 200, message = "库存不足", statue = false });
            }
            #endregion

            string key = dto.MemberId;

            var data = _client.Get<List<ShoppingCarDto>>(key);

            var m = data.Where(x => x.ProductId == dto.ProductId).FirstOrDefault();
            if(m!=null)
            {
                m.ProductNumber = dto.ProductNumber;
            }
            _client.Set(key, data);

            return Ok(new { code = 200, message = "success" });
        }

        /// <summary>
        /// 查询Redis数据
        /// </summary>
        /// <param name="memberId">用户id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Query(string memberId)
        {
            string key = memberId;
            var result = _client.Get<List<ShoppingCarDto>>(key);

            var n = result.GroupBy(x => x.ProductStoreName);


            return Ok(new { code = 200, message = "success", data = result,store= n});
        }
    }


    public class ShoppingCarDto
    {
        /*
         * 这4个字段是必段
         * **/
        public string? MemberId { get; set; } //会员id
        public string? ProductId { get; set; } //商品id
        public int? ProductNumber { get; set; } //商品数量
        public decimal? ProductPrice { get; set; } //商品价格

        /*
         * 这几个是非必须，只是方便显示，不想去数据表联查
         * **/
        public string? ProductName { get; set; } //商品名称
        public string? ProductImage { get; set; } //商品图片
        public string? ProductStoreName { get; set; }  //店铺名称
        public string? Spec { get; set; } //规格
    }
}
